/*
 * Copyright (C) 2015-2016  Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */


#include "PlanetWars2dRT-core/specific/controller/player_robots_utils.h"
#include "PlanetWars2dRT-core/specific/model/ship_position.h"
#include "PlanetWars2dRT-core/specific/model/ship_life.h"
#include "PlanetWars2dRT-core/specific/model/ship_power.h"
#include "PlanetWars2dRT-core/specific/model/planet_position.h"
#include "PlanetWars2dRT-core/specific/model/planet_size.h"
#include "PlanetWars2dRT-core/specific/model/planet_life.h"
#include "PlanetWars2dRT-core/specific/model/universe_ships.h"
#include "PlanetWars2dRT-core/specific/model/game_players.h"


EXTERN_C_BEGIN


unsigned char
player_data_set_as_player_index(const struct game_t* game,
				struct player_t* player)
{
  if(player->data == NULL)
    {
      unsigned char* data_tmp = (unsigned char*) malloc(sizeof(unsigned char));
      *data_tmp = game_get_player_index_of_player(game, player);
      player->data = (void*) data_tmp;
      return *data_tmp;
    }
  return *((unsigned char*) player->data);
}

bool
is_possible_to_attack_planet_for_player(const struct game_t* a_game,
					unsigned char player_index,
					const struct planet_t* planet_to_attack)
{
  const position_2d_uint position_to_attack =
    planet_get_center_position(planet_to_attack);
  unsigned int life_planet_to_attack_and_around =
    planet_get_life_current(planet_to_attack);
  unsigned int power_of_AI = 0;
  
  const unsigned int max_distance_for_a_ship_to_attack =
    2 * planet_get_radius(planet_to_attack);

  const size_t nb = universe_get_nb_ships(&a_game->universe);
  for(size_t i=0; i < nb; ++i)
    {
      const ship_t* ship_i = universe_get_const_ship_no_check(&a_game->universe, i);
      const position_2d_uint ship_position =
	ship_get_center_position_current(ship_i);
      
      if(ship_get_player_index(ship_i) == planet_to_attack->player_index
	 &&
	 distance_between_2_positions_2d_uint(&ship_position, &position_to_attack)
	 < max_distance_for_a_ship_to_attack)
	{
	  life_planet_to_attack_and_around += ship_get_life_current(ship_i);
	}
      if(ship_get_player_index(ship_i) == player_index)
	{
	  power_of_AI += ship_get_power(ship_i);
	}
    }
  return 0.8 * power_of_AI > life_planet_to_attack_and_around;
}


EXTERN_C_END
